package com.inspur.sc.springboot.security;

import com.inspur.sc.springboot.dao.SysRoleDao;
import com.inspur.sc.springboot.dao.SysRoleUserDao;
import com.inspur.sc.springboot.dao.SysUserDao;
import com.inspur.sc.springboot.entity.SysRole;
import com.inspur.sc.springboot.entity.SysRoleUser;
import com.inspur.sc.springboot.entity.SysUser;
import com.inspur.sc.springboot.utils.SpringSecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuchu
 */
@Service
@Slf4j
public class CustomUserService implements UserDetailsService {


    @Autowired
    private SysUserDao userDao;

    @Autowired
    private SysRoleUserDao roleUserDao;

    @Autowired
    private SysRoleDao roleDao;

    @Autowired
    private SessionRegistry sessionRegistry;

    @Value("${user.islogin}")
    private boolean islogin;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,SessionAuthenticationException {
        SysUser user = userDao.findByUsername(username);
        if (user != null) {
            if (user.getStatus() == 1) {
                List<SysRoleUser> sysRoleUsers = roleUserDao.findBySysUserId(user.getId());
                List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                for (SysRoleUser roleUser : sysRoleUsers) {
                    SysRole role = roleDao.findById(roleUser.getSysRoleId()).get();
                    if (role != null && role.getName() != null) {
                        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getName());
                        //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                        grantedAuthorities.add(grantedAuthority);
                    }
                }
                user.setGrantedAuthorities(grantedAuthorities);

                if(!islogin){
                    List<Object> o = sessionRegistry.getAllPrincipals();
                    for ( Object principal : o) {
                        if (principal instanceof SysUser && (user.getUsername().equals(((SysUser) principal).getUsername()))) {
                            throw new SessionAuthenticationException("当前用户已经在线，登录失败！！！");
                        }
                    }
                }else {
                    List<SessionInformation> sessionInformations=sessionRegistry.getAllSessions(user,false);
                    if(!sessionInformations.isEmpty()){
                        SessionInformation sessionInformation=sessionInformations.get(0);
                        if(null != sessionInformation){
                            log.info(sessionInformation.getSessionId());
                            sessionInformation.expireNow();
                        }
                    }
                }
                return user;
            }
            throw new UsernameNotFoundException("用户: " + username + " 已被禁用，不允许登陆，请联系管理员!");
        } else {
            throw new UsernameNotFoundException("用户: " + username + " 不存在!");
        }
    }
}
